/*
 * @Author: 江舟 jijiangzhou@recycloud.cn
 * @Date: 2024-03-28 19:40:39
 * @LastEditors: 江舟 jijiangzhou@recycloud.cn
 * @LastEditTime: 2024-03-29 09:18:10
 * @FilePath: \vite-project\src\hooks\common\useCacheTime.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import { useEffect, useRef, useState } from 'react';

const useCacheTimeCountDown = (duration = 60) => {
	const [timeLeft, setTimeLeft] = useState<number | null>(null);
	const timeRef = useRef<any>();

	const reStart = (d = 60) => {
		setTimeLeft(d);
		timeRef.current = setInterval(() => {
			setTimeLeft(currentTime => {
				if (currentTime) {
					localStorage.setItem(
						'CACHE_TIME_COUNT_DOWN_LEAVE_TIME',
						JSON.stringify({
							timeLeft: currentTime,
							leaveTime: `${new Date().getTime()}`,
						}),
					);
					return currentTime - 1;
				}
				return 0;
			});
		}, 1000);
	};
	const stop = () => {
		if (timeRef.current) {
			localStorage.removeItem('CACHE_TIME_COUNT_DOWN_LEAVE_TIME');
			setTimeLeft(null);
			clearInterval(timeRef.current);
		}
	};

	useEffect(() => {
		const leaveTime = localStorage.getItem('CACHE_TIME_COUNT_DOWN_LEAVE_TIME');
		if (leaveTime) {
			const leaveObj = JSON.parse(leaveTime);
			const d = Number(leaveObj?.timeLeft) - parseInt(`${(new Date().getTime() - Number(leaveObj?.leaveTime)) / 1000}`);
			localStorage.removeItem('CACHE_TIME_COUNT_DOWN_LEAVE_TIME');
			if (d > 0) {
				reStart(d);
			} else {
				stop();
			}
		}
	}, []);

	useEffect(() => {
		if (timeLeft === 0) {
			stop();
		}
	}, [timeLeft]);

	return {
		timeLeft,
		reStart,
	};
};

export default useCacheTimeCountDown;
